import axios from 'axios'
import { Notify } from '@opentiny/vue'
import { useAuthStore } from '@/stores/auth'
import router from '@/router'

// 创建axios实例
const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api',
  timeout: 60000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const authStore = useAuthStore()
    
    // 添加认证token
    if (authStore.token) {
      config.headers = config.headers || {}
      config.headers.Authorization = `Bearer ${authStore.token}`
    }

    // 添加请求时间戳（防止缓存）
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        _t: Date.now()
      }
    }

    return config
  },
  (error) => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    const { data } = response

    // 如果是文件下载等特殊响应，直接返回
    if (response.config.responseType === 'blob') {
      return response
    }

    // 统一处理响应数据
    if (data.code !== undefined) {
      // 成功响应
      if (data.code === 200) {
        return data
      }
      
      // 业务错误
      if (data.code === 401) {
        Notify({ type: 'error', message: '登录已过期，请重新登录' })
        const authStore = useAuthStore()
        authStore.clearAuth()
        router.push('/login')
        return Promise.reject(new Error('未授权访问'))
      }
      
      if (data.code === 403) {
        Notify({ type: 'error', message: '无权限访问' })
        return Promise.reject(new Error('无权限访问'))
      }
      
      // 其他业务错误
      const errorMessage = data.msg || '请求失败'
      Alert({ message: errorMessage })
      return Promise.reject(new Error(errorMessage))
    }

    // 直接返回数据（非标准格式）
    return data
  },
  (error) => {
    console.error('Response error:', error)

    // 网络错误处理
    if (!error.response) {
      Alert({ message: '网络连接异常，请检查网络设置' })
      return Promise.reject(error)
    }

    const { status, data } = error.response

    // HTTP状态码错误处理
    switch (status) {
      case 400:
        Notify({ type: 'error', message: data?.msg || '请求参数错误' })
        break
      case 401:
        Notify({ type: 'error', message: '登录已过期，请重新登录' })
        const authStore = useAuthStore()
        authStore.clearAuth()
        router.push('/login')
        break
      case 403:
        Notify({ type: 'error', message: '无权限访问该资源' })
        break
      case 404:
        Notify({ type: 'error', message: '请求的资源不存在' })
        break
      case 408:
        Notify({ type: 'error', message: '请求超时，请稍后重试' })
        break
      case 429:
        Notify({ type: 'error', message: '请求过于频繁，请稍后重试' })
        break
      case 500:
        Notify({ type: 'error', message: '服务器内部错误' })
        break
      case 502:
        Notify({ type: 'error', message: '网关错误' })
        break
      case 503:
        Notify({ type: 'error', message: '服务暂时不可用' })
        break
      case 504:
        Notify({ type: 'error', message: '网关超时' })
        break
      default:
        Notify({ type: 'error', message: data?.msg || `请求失败 (${status})` })
        break
    }

    return Promise.reject(error)
  }
)

export default request

// 导出常用的请求方法
export const get = (url: string, params?: any) => request.get(url, { params })
export const post = (url: string, data?: any) => request.post(url, data)
export const put = (url: string, data?: any) => request.put(url, data)
export const del = (url: string, params?: any) => request.delete(url, { params })

// 文件上传专用方法
export const upload = (url: string, formData: FormData, onUploadProgress?: (progressEvent: any) => void) => {
  return request.post(url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress
  })
}

// 文件下载专用方法
export const download = (url: string, params?: any) => {
  return request.get(url, {
    params,
    responseType: 'blob'
  })
}